<template>
  <div>
    <div class="tag-box">
      <template v-for="(tag, index) in tags1">
        <CloudTooltip v-if="tag.length > 20" :key="tag" :title="tag">
          <CloudTag :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
            {{ `${tag.slice(0, 20)}...` }}
          </CloudTag>
        </CloudTooltip>
        <CloudTag v-else :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
          {{ tag }}
        </CloudTag>
      </template>
      <CloudInput
        v-if="inputVisible"
        ref="input"
        type="text"
        size="small"
        :style="{ width: '78px' }"
        :value="inputValue"
        placeholder=""
        @change="handleInputChange"
        @blur="handleInputConfirm"
        @keyup.enter="handleInputConfirm"
      />
      <CloudTag v-else style="background: #fff; border: 1px dashed #d9d9d9" @click="showInput">
        <CloudIcon type="plus" /> New Tag
      </CloudTag>
    </div>
  </div>
</template>

<script>
  export default {
    title: '5.动态添加和删除',
    subTitle: '用数组生成一组标签，可以动态添加和删除。',
    data () {
      return {
        tags1: ['Unremovable', 'Tag 2', 'Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3Tag 3'],
        inputVisible: false,
        inputValue: ''
      }
    },
    methods: {
      handleClose (removedTag) {
        const tags = this.tags1.filter(tag => tag !== removedTag);
        console.log(tags);
        this.tags1 = tags;
      },

      showInput () {
        this.inputVisible = true;
        this.$nextTick(function () {
          console.log('wwwww', this.$refs.input)
          this.$refs.input.focus();
        });
      },

      handleInputChange (e) {
        this.inputValue = e.target.value;
      },

      handleInputConfirm () {
        const inputValue = this.inputValue;
        let tags = this.tags1;
        if (inputValue && tags.indexOf(inputValue) === -1) {
          tags = [...tags, inputValue];
        }
        console.log(tags);
        Object.assign(this, {
          tags1: tags,
          inputVisible: false,
          inputValue: '',
        });
      }
    }
  }
</script>

<style lang="scss">
</style>